package com.chidt.zpro.controller;


import cn.hutool.crypto.SecureUtil;
import com.chidt.zpro.entity.User;
import com.chidt.zpro.service.UserService;
import com.chidt.zpro.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

/**
 * 用户登录
 */
@WebServlet("/user/login")
public class UserLoginController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("email");
        String password = req.getParameter("password");

        UserService userService = new UserServiceImpl();
        try {
            User user = userService.login(username, password);
            if (user != null) {
                req.getSession().setAttribute("loginUser", user);
                resp.sendRedirect(req.getContextPath() + "/index.jsp");
                System.out.println("登录成功,Session.User:"+req.getSession().getAttribute("loginUser"));
                return;
            }
            goLogin(req, resp, "用户名或密码错误");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    public static void goLogin(HttpServletRequest req, HttpServletResponse resp,String msg) throws ServletException, IOException {
        req.setAttribute("msg", msg);
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }

    public static void main(String[] args) {

    }
}
